using System;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Coderoom.ScrumPlanner.Resources;
using Coderoom.ScrumPlanner.Utilities;
using ClrConfigManager = System.Configuration.ConfigurationManager;

namespace Coderoom.ScrumPlanner.Configuration
{
	public sealed class ConfigurationManager
	{
		private static string _xmlRepositoryDataDirectoryPath;

		internal ConfigurationManager() {}

		[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
		public static string GetXmlRepositoryDataDirectoryPath()
		{
			if (_xmlRepositoryDataDirectoryPath == null)
			{
				if (string.IsNullOrEmpty(ClrConfigManager.AppSettings.Get(KnownConfigurationKeys.XmlRepositoryDataDirectoryPath)))
					throw new ConfigurationErrorsException(ExceptionMessages.ConfigurationErrorsException_ConfigurationEntryNotFound.Inject(KnownConfigurationKeys.XmlRepositoryDataDirectoryPath));

				var value = ClrConfigManager.AppSettings[KnownConfigurationKeys.XmlRepositoryDataDirectoryPath];

				if (value.StartsWith("~", StringComparison.OrdinalIgnoreCase) || Path.IsPathRooted(value))
				{
					// this is a virtual path or absolute path
					_xmlRepositoryDataDirectoryPath = value;
				}
				else
				{
					// this is a relative path - prepend working directory
					_xmlRepositoryDataDirectoryPath = Path.Combine(Environment.CurrentDirectory, value);
				}
			}

			return _xmlRepositoryDataDirectoryPath;
		}

		#region Nested type: KnownConfigurationKeys

		private struct KnownConfigurationKeys
		{
			internal static string XmlRepositoryDataDirectoryPath
			{
				get { return "Data.Repositories.Xml.DataDirectoryPath"; }
			}
		}

		#endregion
	}
}